package com.example.backend.service.impl;

import com.example.backend.common.utils.JwtUtils;
import com.example.backend.service.TokenService;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
@RequiredArgsConstructor
public class TokenServiceImpl implements TokenService {
    
    private final RedisTemplate<String, String> redisTemplate;
    private final JwtUtils jwtUtils;
    
    private static final String TOKEN_KEY_PREFIX = "token:user:";
    private static final long RENEW_THRESHOLD = 12 * 60 * 60 * 1000; // 12小时
    
    @Override
    public void storeToken(Long userId, String token) {
        String key = TOKEN_KEY_PREFIX + userId;
        // 如果已存在Token，先删除旧Token
        String oldToken = redisTemplate.opsForValue().get(key);
        if (oldToken != null) {
            // 将旧Token加入黑名单
            jwtUtils.invalidateToken(oldToken);
        }
        // 存储新Token
        redisTemplate.opsForValue().set(key, token, jwtUtils.getExpiration(), TimeUnit.MILLISECONDS);
    }
    
    @Override
    public String getToken(Long userId) {
        return redisTemplate.opsForValue().get(TOKEN_KEY_PREFIX + userId);
    }
    
    @Override
    public void removeToken(Long userId) {
        redisTemplate.delete(TOKEN_KEY_PREFIX + userId);
    }
    
    @Override
    public boolean needRenew(String token) {
        Long expiration = jwtUtils.getExpirationFromToken(token);
        return expiration - System.currentTimeMillis() < RENEW_THRESHOLD;
    }
    
    @Override
    public String renewToken(String token) {
        // 获取原Token中的信息
        String username = jwtUtils.getUsernameFromToken(token);
        Map<String, Object> claims = jwtUtils.getClaimsFromToken(token);
        // 生成新Token
        return jwtUtils.generateToken(username, claims);
    }
} 